package com.onemile.app;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;

import org.xmlpull.v1.XmlSerializer;

import com.onemile.app.base.BaseUINoBottom;
import com.onemile.data.DXml;
import com.onemile.entity.MessageCode;
import com.onemile.entity.PubConst;
import com.onemile.entity.Session;
import com.onemile.entity.model.EAddress;
import com.onemile.net.NetClient;
import com.onemile.utils.UtiDialogsFactory;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class UISettlementAddressNewEdit extends BaseUINoBottom
{
   private boolean ISNEW;
   private EAddress mAddress;

   private EditText edtConsignee;
   private EditText edtMobile;
   private EditText edtAddress;
   private EditText edtName;

   private Button btnOK;
   private Button btnCancel;

   // private ArrayList<EProvinceCity> listProvince;
   // private ArrayList<EProvinceCity> listCity;

   private LayoutInflater mInflater;

   private void InitControls()
   {
	  mInflater = LayoutInflater.from(this);
	  edtConsignee = (EditText) findViewById(R.id.edtConsignee_settleaddress_newedit);
	  edtMobile = (EditText) findViewById(R.id.edtMobile__settleaddress_newedit);
	  edtAddress = (EditText) findViewById(R.id.edtAddress_settleaddress_newedit);
	  edtName = (EditText) findViewById(R.id.edtName_settleaddress_newedit);

	  btnOK = (Button) findViewById(R.id.btnOK_settleaddress_newedit);
	  btnCancel = (Button) findViewById(R.id.btnCancel_settleaddress_newedit);

   }

   private void InitControlsEvent()
   {

	  btnOK.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			try
			{
			   if (VerifyInfo())
			   {
				  EAddress eAddress = new EAddress();
				  eAddress.setUserAddressId(String.valueOf(edtName.getTag()));
				  eAddress.setUserId(Session.getInstance().getUserInfo().getUserId());
				  eAddress.setAddressName(edtName.getText().toString().trim());
				  eAddress.setMobile(edtMobile.getText().toString().trim());
				  eAddress.setConsignee(edtConsignee.getText().toString().trim());
				  eAddress.setAddress(edtAddress.getText().toString().trim());
				  eAddress.setRec_ModifyBy(Session.getInstance().getUserInfo().getUserName());
                  eAddress.setRec_CreateBy(Session.getInstance().getUserInfo().getUserName());
				  if (ISNEW)
				  {
					 executeAsyncTask(PubConst.TaskName.SETTLE_ADDRESS_NEW, new Object[] { eAddress });
				  }
				  else
				  {
					 executeAsyncTask(PubConst.TaskName.SETTLE_ADDRESS_EDIT, new Object[] { eAddress });
				  }
			   }
			}
			catch (Exception e)
			{
			   if (Session.getInstance().IsDEBUG())
			   {
				  Log.e("ERROR", "UISettlementAddressNewEdit.InitControlsEvent().new OnClickListener() {...}_onClick(v) ", e);
			   }
			}
		 }
	  });

	  btnCancel.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			Session.getInstance().CleanAddressCache();
			setResult(RESULT_CANCELED);
			finish();
		 }
	  });
   }

   private boolean VerifyInfo()
   {
	  if (edtName.getText().toString().trim() == null || edtName.getText().toString().trim().equals(""))// 地址名称为空
	  {
		 UtiDialogsFactory.getInstance().ShowToastInfoShort(UISettlementAddressNewEdit.this, getString(R.string.adr_name_not_empty));
		 return false;
	  }
	  else if (edtMobile.getText().toString().trim() == null || edtMobile.getText().toString().trim().equals(""))// 电话为空
	  {
		 UtiDialogsFactory.getInstance().ShowToastInfoShort(UISettlementAddressNewEdit.this, getString(R.string.adr_mobile_not_empty));
		 return false;
	  }
	  else if (edtAddress.getText().toString().trim() == null || edtAddress.getText().toString().trim().equals(""))// 地址为空
	  {
		 UtiDialogsFactory.getInstance().ShowToastInfoShort(UISettlementAddressNewEdit.this, getString(R.string.adr_address_not_empty));
		 return false;
	  }
	  return true;
   }

   @Override
   protected void onCreateOverride(Bundle savedInstanceState)
   {
	  try
	  {
		 InitControls();
		 if (!ISNEW)
		 {
			if (Session.getInstance().getAddressCache() != null)
			{
			   edtConsignee.setText(Session.getInstance().getAddressCache().getConsignee());
			   edtMobile.setText(Session.getInstance().getAddressCache().getMobile());
			   edtAddress.setText(Session.getInstance().getAddressCache().getAddress());
			   edtName.setText(Session.getInstance().getAddressCache().getAddressName());
			   edtName.setTag(Session.getInstance().getAddressCache().getUserAddressId());

			   Session.getInstance().CleanAddressCache();
			}

		 }
		 InitControlsEvent();
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIOrderAddressNewEdit_onCreateOverride(savedInstanceState) ", e);
		 }
	  }
   }

   @Override
   public int SetContentViewLayoutResId()
   {
	  return R.layout.settlement_address_new_edit;
   }

   @Override
   public boolean onKeyDown(int keyCode, KeyEvent event)
   {
	  if (keyCode == event.KEYCODE_BACK)
	  {
		 Session.getInstance().CleanAddressCache();
		 setResult(RESULT_CANCELED);
		 finish();
	  }
	  return false;
   }

   @Override
   public void SetTopToolbar(TextView topTxt, ImageView leftImBtn, ImageView rightImgBtn, RelativeLayout rightRay, TextView cartNum)
   {
	  ISNEW = getIntent().getBooleanExtra(PubConst.Intent_Key.IS_NEW_ADDRESS, false);
	  topTxt.setVisibility(View.VISIBLE);
	  if (ISNEW)
	  {
		 topTxt.setText(getString(R.string.title_address_new));
	  }
	  else
	  {
		 topTxt.setText(getString(R.string.title_address_edit));
	  }
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UISettlementAddressNewEdit.this, getString(R.string.dialog_uploading));
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  try
	  {
		 if (taskName != null && taskName.equals(PubConst.TaskName.SETTLE_ADDRESS_NEW))
		 {
			return NetClient.InsertNewAddress((EAddress) params[0]);
		 }
		 if (taskName != null && taskName.equals(PubConst.TaskName.SETTLE_ADDRESS_EDIT))
		 {
			return NetClient.EditAddress((EAddress) params[0]);
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UISettlementAddressNewEdit_onAsyncTaskInBackground(taskName, params) ", e);
		 }
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  try
	  {
		 UtiDialogsFactory.getInstance().DismissLoadingDialog();
		 if (result != null)
		 {
			DXml data = (DXml) result;
			if (taskName.equals(PubConst.TaskName.SETTLE_ADDRESS_NEW) || taskName.equals(PubConst.TaskName.SETTLE_ADDRESS_EDIT))
			{
			   if (data.getHead().GetFieldValue("RspCode").equals(MessageCode.Success.Code))
			   {
				  UtiDialogsFactory.getInstance().ShowOKAlertDialog(UISettlementAddressNewEdit.this, getString(R.string.dialog_tips), getString(R.string.dialog_uploading_success),
						new DialogInterface.OnClickListener()
						{
						   @Override
						   public void onClick(DialogInterface dialog, int which)
						   {
							  dialog.dismiss();
							  Session.getInstance().CleanAddressCache();
							  setResult(RESULT_OK);
							  finish();
						   }
						});
			   }
			   else
			   {
				  UtiDialogsFactory.getInstance().ShowToastInfoShort(UISettlementAddressNewEdit.this,data.getHead().GetFieldValue("RspMsg"));
			   }
			}
		 }
		 else
		 {
			UtiDialogsFactory.getInstance().ShowToastInfoShort(UISettlementAddressNewEdit.this, getString(R.string.dialog_server_failed));
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UISettlementAddressNewEdit_onAsyncTaskEnd(taskId, taskName, params, result) ", e);
		 }
		 UtiDialogsFactory.getInstance().ShowToastInfoShort(UISettlementAddressNewEdit.this, getString(R.string.dialog_uploading_failed));
	  }
   }

}
